package spring.cloud.tasks.executor.executor;

import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import spring.cloud.tasks.executor.executor.task.Lifecycle;
import spring.cloud.tasks.executor.executor.task.task_item_allot.ExecutorTaskTriggerTask;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Setter
@Getter

public class ExecutorTaskTriggerService implements Lifecycle {

    private String executorId;
    private ScheduledExecutorService scheduledExecutorService;

    public ExecutorTaskTriggerService(@NonNull String executorId) {
        this.executorId = executorId;
    }

    @Override
    public void start() {

        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
            private final AtomicInteger number = new AtomicInteger(0);

            @Override
            public Thread newThread(Runnable runnable) {
                StringBuilder name = new StringBuilder().append("-ProcessCount-Thread-").append(number.incrementAndGet());
                Thread thread = new Thread(runnable, name.toString());
                thread.setDaemon(false);
                thread.setPriority(Thread.NORM_PRIORITY);
                return thread;
            }
        });
        scheduledExecutorService.scheduleAtFixedRate(new ExecutorTaskTriggerTask(executorId), 0, 15, TimeUnit.SECONDS);
    }

    @Override
    public void stop() {

    }

}
